# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:

from MysqlTools import MysqlTools
import json
import hashlib

class ParseLevelData:

    def __init__(self, **kwargs):
        self.db = MysqlTools(db_config=kwargs.get("db_config"), type='dict')
        self.src_table = kwargs.get("src_table")
        self.group_table = kwargs.get("group_table")
        self.structrue_table = kwargs.get("structrue_table")
        self.part_num_table = kwargs.get("part_num_table")
        self.group_structrue_dict = {}
        self.Cid = None

    def get_cid_list(self):
        '''获取cid列表'''
        sql = '''select distinct `level1_code` from `{}`'''.format(self.src_table)
        data = self.db.select_all(sql)
        _l = [i.get("level1_code") for i in data]
        # _l = ["3688061_2010"]
        return _l

    def get_cid_info(self, cid):
        '''获取单个cid下的所有层级数据'''
        sql = '''select * from `{}` where `level1_code`="{}"'''.format(self.src_table, cid)
        data = self.db.select_all(sql)
        return data

    def get_md5(self, str):
        '''获取md5加密电子指纹'''
        md5 = hashlib.md5()
        md5.update(str)
        return md5.hexdigest()

    def get_group_dict(self):
        sql = '''select * from `strcture_name_finally`'''
        data = self.db.select_all(sql)
        _dict = {}
        for i in data:
            k = i.get("structrue_name").strip().replace('\n','')
            group_name = i.get("group_name")
            group_num = i.get("group_num")
            _dict[k] = {"name": group_name, "num": group_num}
        self.group_structrue_dict = _dict
    # def construct_cid_info_dict(self, cid_info):
    #     '''把单个cid下的所有层级数据构造成字典'''
    #     _dict = {i.get("level3_code"): {} for i in cid_info}
    #     for i in cid_info:
    #         level3_code = i.get("level3_code")
    #         level3_name = i.get("level3_name")
    #         _dict[level3_code]["name"]=level3_name
    #         _dict[level3_code]["next"]={}
    #         level4_code = i.get("level4_code")
    #         level4_name = i.get("level4_name")
    #         if level4_code not in _dict[level3_code]:
    #             _dict[level3_code]["next"][level4_code]={}
    #             _dict[level3_code]["next"][level4_code]["name"]=level4_name
    #         else:
    #             _dict[level3_code]["next"]

    def save_group(self, dict):
        sql_tail = ' on duplicate key update brandCode=values(`brandCode`)'
        sql = self.db.get_insert_sql(self.group_table, dict)
        self.db.execute_sql(sql + sql_tail)

    def save_structrue(self, dict):
        sql_tail = ' on duplicate key update brandCode=values(`brandCode`)'
        sql = self.db.get_insert_sql(self.structrue_table, dict)
        self.db.execute_sql(sql+sql_tail)

    def save_part_num(self, dict):
        sql = self.db.get_insert_sql(self.part_num_table, dict)
        sql_tail = ' on duplicate key update brandCode=values(`brandCode`)'
        self.db.execute_sql(sql+sql_tail)

    def handle_one(self, data):
        '''第四层就是零件'''
        level3_code = data.get("level3_code")  # 获取层级号
        level4_code = data.get("level4_code")
        level3_name = data.get("level3").strip().replace("\n", "")  # 获取层级名
        level4_name = data.get("level4").strip().replace("\n", "")
        imgPoint = json.loads(data.get("imgPoint"))
        raw_info = json.loads(data.get("raw_info"))
        try:
            group_name = self.group_structrue_dict.get(level3_name).get("name")  # 获取主组名及主组号
        except:
            print(level3_name)
            exit()
        group_num = self.group_structrue_dict.get(level3_name).get("num")
        str1 = self.Cid+group_num+group_name
        str2 = self.Cid+group_num+level3_code+level3_name
        group__dict = dict(
            uid=self.get_md5(str1.encode()),
            cid=self.Cid,
            num=group_num,
            brandCode="jac",
            label=group_name,
            extra_info='',
            updatetime='now()',
            createtime='now()'
        )
        structrue_dict = dict(
            uid=self.get_md5(str2.encode()),
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level3_code,
            mid=level3_code,
            brandCode="jac",
            name=level3_name,
            description='',
            model='',
            condition='',
            imgName=level3_code+'.png',
            imgPoints='',  # 后期再次清洗
            logo='',
            extra_info=json.dumps(raw_info.get("level3"), ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        is_no = {
            '0':'否',
            '1':'是'
        }
        level4_dict = raw_info.get("level4")
        level4_dict['imgPoint'] = imgPoint
        part_num_dict = dict(
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level3_code,
            mid=level3_code,
            brandCode="jac",
            pnum=level4_dict.get("psort"),
            itid='',
            psort=0,
            pid=level4_code,
            label=level4_name,
            remark=level4_dict.get("remark"), # 备注
            quantity=level4_dict.get("qty"), # 数量
            model='是否备件: {}, 是否停用: {}'.format(is_no.get(level4_dict.get("isspare")),is_no.get(level4_dict.get("isstop"))),
            isreplace='',
            replacelabel='',
            rid='',
            condition='',
            img='',
            logo='',
            price='',
            extra_info=json.dumps(level4_dict, ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        self.save_group(group__dict)
        self.save_structrue(structrue_dict)
        self.save_part_num(part_num_dict)


    def handle_two(self, data):
        level3_code = data.get("level3_code")  # 获取层级号
        level4_code = data.get("level4_code")
        level5_code = data.get("level5_code")
        level6_code = data.get("level6_code")
        level3_name = data.get("level3").strip().replace("\n", "")  # 获取层级名
        level4_name = data.get("level4").strip().replace("\n", "")
        level5_name = data.get("level5").strip().replace("\n", "")
        level6_name = data.get("level6").strip().replace("\n", "")
        imgPoint = json.loads(data.get("imgPoint"))
        raw_info = json.loads(data.get("raw_info"))
        try:
            group_name = self.group_structrue_dict.get(level3_name).get("name")  # 获取主组名及主组号
        except:
            print(level3_name)
            exit()
        group_num = self.group_structrue_dict.get(level3_name).get("num")
        str1 = self.Cid+group_num+group_name
        str2 = self.Cid+group_num+level4_code+level4_name
        group__dict = dict(
            uid=self.get_md5(str1.encode()),
            cid=self.Cid,
            num=group_num,
            brandCode="jac",
            label=group_name,
            extra_info='',
            updatetime='now()',
            createtime='now()'
        )
        structrue_dict = dict(
            uid=self.get_md5(str2.encode()),
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level4_code,
            mid=level4_code,
            brandCode="jac",
            name=level4_name,
            description='',
            model='',
            condition='',
            imgName=level4_code + '.png',
            imgPoints='',  # 后期再次清洗
            logo='',
            extra_info=json.dumps(raw_info.get("level4"), ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        is_no = {
            '0': '否',
            '1': '是'
        }
        level5_dict = raw_info.get("level5")
        level5_dict['imgPoint'] = imgPoint
        part_num_dict = dict(
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level4_code,
            mid=level4_code,
            brandCode="jac",
            pnum=level5_dict.get("psort"),
            itid='',
            psort=0,
            pid=level5_code,
            label=level5_name,
            remark=level5_dict.get("remark"),  # 备注
            quantity=level5_dict.get("qty"),  # 数量
            model='是否备件: {}, 是否停用: {}'.format(is_no.get(level5_dict.get("isspare")),
                                              is_no.get(level5_dict.get("isstop"))),
            isreplace='',
            replacelabel='',
            rid='',
            condition='',
            img='',
            logo='',
            price='',
            extra_info=json.dumps(level5_dict, ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        self.save_group(group__dict)
        self.save_structrue(structrue_dict)
        self.save_part_num(part_num_dict)

    def handle_three(self, data):
        level3_code = data.get("level3_code")  # 获取层级号
        level4_code = data.get("level4_code")
        level5_code = data.get("level5_code")
        level6_code = data.get("level6_code")
        level3_name = data.get("level3").strip().replace("\n", "") # 获取层级名
        level4_name = data.get("level4").strip().replace("\n", "")
        level5_name = data.get("level5").strip().replace("\n", "")
        level6_name = data.get("level6").strip().replace("\n", "")
        imgPoint = json.loads(data.get("imgPoint"))
        raw_info = json.loads(data.get("raw_info"))
        try:
            group_name = self.group_structrue_dict.get(level3_name).get("name")  # 获取主组名及主组号
        except:
            print(level3_name)
            exit()
        group_num = self.group_structrue_dict.get(level3_name).get("num")
        str1 = self.Cid + group_num + group_name
        str2 = self.Cid + group_num + level4_code + level4_name
        group__dict = dict(
            uid=self.get_md5(str1.encode()),
            cid=self.Cid,
            num=group_num,
            brandCode="jac",
            label=group_name,
            extra_info='',
            updatetime='now()',
            createtime='now()'
        )
        structrue_dict = dict(
            uid=self.get_md5(str2.encode()),
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level4_code,
            mid=level4_code,
            brandCode="jac",
            name=level4_name,
            description='',
            model='',
            condition='',
            imgName=level4_code + '.png',
            imgPoints='',  # 后期再次清洗
            logo='',
            extra_info=json.dumps(raw_info.get("level4"), ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        is_no = {
            '0': '否',
            '1': '是'
        }
        level5_dict = raw_info.get("level5")
        level5_dict['imgPoint'] = imgPoint
        part_num_dict = dict(
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level4_code,
            mid=level4_code,
            brandCode="jac",
            pnum=level5_dict.get("psort"),
            itid='',
            psort=0,
            pid=level5_code,
            label=level5_name,
            remark=level5_dict.get("remark"),  # 备注
            quantity=level5_dict.get("qty"),  # 数量
            model='是否备件: {}, 是否停用: {}'.format(is_no.get(level5_dict.get("isspare")),
                                              is_no.get(level5_dict.get("isstop"))),
            isreplace='',
            replacelabel='',
            rid='',
            condition='',
            img='',
            logo='',
            price='',
            extra_info=json.dumps(level5_dict, ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        level6_dict = raw_info.get("level6")
        level6_dict['imgPoint'] = imgPoint
        part_num_dict_6 = dict(
            cid=self.Cid,
            num=group_num,
            maingroup=group_num,
            subgroup=level4_code,
            mid=level4_code,
            brandCode="jac",
            pnum=level5_dict.get("psort"),
            itid='',
            psort=0,
            pid=level6_code,
            label=level6_name,
            remark=level6_dict.get("remark"),  # 备注
            quantity=level6_dict.get("qty"),  # 数量
            model='是否备件: {}, 是否停用: {}'.format(is_no.get(level6_dict.get("isspare")),
                                              is_no.get(level6_dict.get("isstop"))),
            isreplace='',
            replacelabel='',
            rid='',
            condition='',
            img='',
            logo='',
            price='',
            extra_info=json.dumps(level6_dict, ensure_ascii=False),
            updatetime='now()',
            createtime='now()'
        )
        self.save_group(group__dict)
        self.save_structrue(structrue_dict)
        self.save_part_num(part_num_dict)
        self.save_part_num(part_num_dict_6)


    def handle_cid_level_data(self, cid):
        cid_info = self.get_cid_info(cid)
        for data in cid_info:

            level5_code = data.get("level5_code")
            level6_code = data.get("level6_code")
            level5_name = data.get("level5")
            level6_name = data.get("level6")
            level3_name = data.get("level3")
            is_l5 = not (level5_name == level5_code)  # 是否有此层级
            is_l6 = not (level6_name == level6_code)

            # 和悦RS
            # if "和悦RS" in level3_name:
            #     continue

            # 分为几种情况
            # 1. level4就是零件层, 没有l5,没有l6
            if not is_l5 and not is_l6:
                self.handle_one(data)

            # 2. level5是零件层, 有l5,没有l6
            elif is_l5 and not is_l6:
                self.handle_two(data)

            # 3. level5及l6都是零件层, 有l5,有l6
            elif is_l5 and is_l5:
                self.handle_three(data)

            else:
                print("特殊情况")
                print(cid)
                exit(0)
        self.db.commit_sql()

    def run(self):
        # 获取cid列表
        self.get_group_dict()
        cid_list = self.get_cid_list()
        # 处理单个cid下所有层级数据
        for cid in cid_list:
            self.Cid = cid
            self.handle_cid_level_data(cid)


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="JAC",
        charset="utf8",
    )
    src_table = 'all_level_info_RS'
    group_table = 'cars_group_collection'
    structrue_tabl = 'cars_structure_collection'
    part_num_table = 'cars_part_num'
    tools = ParseLevelData(db_config=db_config, src_table=src_table, group_table=group_table, structrue_table=structrue_tabl, part_num_table=part_num_table)
    tools.run()
